package com.dm.logistics.basticmanage.controller;

import com.dm.logistics.basticmanage.model.BasticInfo;
import com.dm.logistics.basticmanage.service.BasticService;
import com.dm.logistics.common.util.ExcelUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

@Transactional
@Controller
@CrossOrigin
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired
    private BasticService basticService;

    /**
         * @Description 查询所有固定资产基本信息
         * @Author zhangxue
         * @Date 14:52 2018/5/5
         * @Param
         * @retrun
         **/
    @RequestMapping(value = "/queryAllBasicEqu",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryAllBasicEqu(@RequestBody Map<String,Object> param, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        Map<String,Object> resultMap = basticService.queryAllBasicEqu(param);
        String result = resultMap.get("serviceList")!=null?resultMap.get("serviceList").toString():null;
        return result;
    }

    /**
     * @Description 查询所有固定资产基本信息
     * @Author zhangxue
     * @Date 14:52 2018/5/5
     * @Param
     * @retrun
     **/
    @RequestMapping(value = "/queryAllBasicEqu2",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryAllBasicEqu2(@RequestBody Map<String,Object> param, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        Map<String,Object> resultMap = basticService.queryAllBasicEqu(param);
        String result = resultMap.get("serviceList")!=null?resultMap.get("serviceList").toString():null;
        return result;
    }

    @RequestMapping(value = "/queryAllBasicEqu3",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryAllBasicEqu3(@RequestBody Map<String,Object> param, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        Map<String,Object> resultMap = basticService.queryAllBasicEqu3(param);
        String result = resultMap.get("serviceList")!=null?resultMap.get("serviceList").toString():null;
        return result;
    }

    /**
         * @Description 通过id查询资产信息
         * @Author zhangxue
         * @Date 10:34 2018/5/8
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/queryBasicEquById",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryBasicEquById(@RequestBody Map<String,Object> map) {
        Map<String,Object> resultMap = basticService.queryBasicEquById(map);
        JSONObject jsonObject = JSONObject.fromObject(resultMap);
        return jsonObject.toString();
    }

    /**
         * @Description  通过设备id查询设备维修历程信息
         * @Author zhangxue
         * @Date 15:17 2018/5/7
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/queryBasicEquCourseById",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryBasicEquCourseById(@RequestBody Map<String,Object> map) {
        Map<String,Object> resultMap = basticService.queryBasicEquCourseById(map);
        String result = resultMap.get("serviceList")!=null?resultMap.get("serviceList").toString():null;
        return result;
    }

    /**
         * @Description 保存新增资产信息
         * @Author zhangxue
         * @Date 9:54 2018/5/9
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/saveBasicEqu",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String saveBasicEqu(@RequestBody Map<String,Object> map) {
        Map<String,Object> resultMap = basticService.saveBasicEqu(map);
        JSONObject jsonObject = JSONObject.fromObject(resultMap);
        return jsonObject.toString();
    }

    /**
         * @Description  通过资产编号查看是否存在相同资产编号的资产
         * @Author zhangxue
         * @Date 18:45 2018/5/16
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/queryBasicEquByEquNo",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryBasicEquByEquNo(@RequestBody Map<String,Object> map) {
        Map<String,Object> resultMap = basticService.queryBasicEquByEquNo(map);
        JSONObject jsonObject = JSONObject.fromObject(resultMap);
        return jsonObject.toString();
    }


    /**
         * @Description  上传图片
         * @Author zhangxue
         * @Date 17:33 2018/5/12
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/uploadImage",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String uploadImage(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        String EquNo = request.getParameter("EquNo")!=null?request.getParameter("EquNo").toString():null;
        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        URL path = IndexController.class.getResource("/static/images");
        String filePath = path.getPath()+"/"+EquNo+"/";
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);

        // 检测是否存在目录
        String saveUrl = EquNo+"/"+fileName;
        //將图片路径存入数据库中
        Map<String,Object> imageParam = new HashMap<String,Object>();
        imageParam.put("ImageUrl",saveUrl);
        imageParam.put("EquNo",EquNo);
        Map<String,Object> imgResMap = basticService.saveEquImageInfos(imageParam);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
    /**
         * @Description 数据库中保存图片信息
         * @Author zhangxue
         * @Date 11:31 2018/5/15
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/saveEquImageInfos",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String saveEquImageInfos(@RequestBody Map<String,Object> map) {
        Map<String,Object> resultMap = basticService.saveEquImageInfos(map);
        JSONObject jsonObject = JSONObject.fromObject(resultMap);
        return jsonObject.toString();
    }
    /**
         * @Description 得到所有图片的base64格式
         * @Author zhangxue
         * @Date 8:29 2018/5/14
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/queryImageUrlByEquNo",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryImageUrlByEquNo(@RequestBody Map<String,Object> map) {

        Map<String,Object> imgResMap = basticService.queryImageUrlByEquNo(map);
        JSONObject jsonObject = JSONObject.fromObject(imgResMap);

        return jsonObject.toString();
    }

    /**
         * @Description 通过id删除单条数据
         * @Author zhangxue
         * @Date 15:15 2018/5/12
         * @Param
         * @retrun
         **/
    @RequestMapping(value="/delBasicEquById",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String delBasicEquById(@RequestBody Map<String,Object> map) {

        Map<String,Object> StatusMap = basticService.delBasicEquById(map);
        JSONObject jsonObject = JSONObject.fromObject(StatusMap);
        return jsonObject.toString();
    }

    /**
     * @Description 通过资产编号修改资产基本信息
     * @Author zhangxue
     * @Date 15:15 2018/5/12
     * @Param
     * @retrun
     **/
    @RequestMapping(value="/updateBasicEquByEquNo",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String updateBasicEquByEquNo(@RequestBody Map<String,Object> map) {

        Map<String,Object> StatusMap = basticService.updateBasicEquByEquNo(map);
        JSONObject jsonObject = JSONObject.fromObject(StatusMap);
        return jsonObject.toString();
    }

    /**
     * @Description 导出Excel
     * @Author zhangxue
     * @Date 14:55 2018/6/14
     * @Param
     * @retrun
     **/
    @RequestMapping(value="/CreateBasicExcel",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> CreateBasicExcel(@RequestBody Map<String,Object> param){
        Map<String,Object> statusMap = basticService.CreateAssessExcel(param);
        return statusMap;
    }



    /**
         * @Description  导入资产信息数据
         * @Author zhangxue
         * @Date 17:37 2018/5/22
         * @Param
         * @retrun
         **/
    @Autowired
    private ExcelUtil excelUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @RequestMapping(value = "/saveExcel",method = RequestMethod.POST)
    @ResponseBody
    public int[] insertUserWithKey(){
        File file = new File("E:\\录入\\录入2.xls");
        int[] ints = null;
        try {
            InputStream is = new FileInputStream(file);
            LinkedHashMap<String,String> fieldMap = new LinkedHashMap();
            fieldMap.put("资产名称","EquName");
            fieldMap.put("使用寿命（年）","LifeTime");
            fieldMap.put("购入日期","BuyInTime");
            fieldMap.put("使用状况","ServCondition");
            fieldMap.put("购买费用（元）","BuyInMoney");
            fieldMap.put("开始使用  时   间","StartTime");
            fieldMap.put("截止使用  时   间","EndTime");
            fieldMap.put("设备类别","EquType");
            fieldMap.put("购置方式","PurchaseType");
            fieldMap.put("中心店面","Store");
            fieldMap.put("所处状态","EquStatus");
            fieldMap.put("设备编号","EquNo");
            fieldMap.put("维护周期（天）","ConsePeriod");
            fieldMap.put("型号-规格","Specification");
            fieldMap.put("安装地点","Place");
            fieldMap.put("录入人","InputMan");

            String[] uniqueFileds = {"设备编号"};
            List<BasticInfo> resultList = excelUtil.excelToList(is,"basticinfo", BasticInfo.class,fieldMap,uniqueFileds);
            String sql = "INSERT INTO [EquBasic]\n" +
                    "           ([EquName]\n" +
                    "           ,[LifeTime]\n" +
                    "           ,[StartTime]\n" +
                    "           ,[EndTime]\n" +
                    "           ,[BuyInMoney]\n" +
                    "           ,[EquType]\n" +
                    "           ,[PurchaseType]\n" +
                    "           ,[Store]\n" +
                    "           ,[EquStatus]\n" +
                    "           ,[EquNo]\n" +
                    "           ,[ConsePeriod]\n" +
                    "           ,[Specification]\n" +
                    "           ,[Place]\n" +
                    "           ,[ServCondition]\n" +
                    "           ,[BuyInTime]\n" +
                    "           ,[InputMan])\n" +
                    "     VALUES\n" +
                    "           (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            ints = jdbcTemplate.batchUpdate(sql, setParameters(resultList));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ints;
    }

    /**
     * 设置参预置数
     * @param listBastic
     * @return
     */
    private static List<Object[]> setParameters(List<BasticInfo> listBastic){
        List<Object[]> parameters = new ArrayList<Object[]>();
        for (BasticInfo u : listBastic) {
            parameters.add(new Object[] { u.getEquName(),u.getLifeTime(),u.getStartTime(),u.getEndTime(),u.getBuyInMoney(),u.getEquType(),u.getPurchaseType(),u.getStore(),u.getEquStatus(),u.getEquNo(),u.getConsePeriod(),u.getSpecification(),u.getPlace(),u.getServCondition(),u.getBuyInTime(),u.getInputMan()});
        }
        return parameters;
    }

}
